package com.ubxtech.db.generator;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.builder.CustomFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.ubxtech.db.entity.Entity;
import org.apache.ibatis.type.JdbcType;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author Victor.Xiao
 * @since 2022-01-11 16:29
 **/
public class CodeGenerator {
    public static void generator(String tableName,String host,int port,String dbName,String dbUser,String dbPassword,String output,String moduleName,String author) {
        generator(Arrays.asList(tableName),host,port,dbName,dbUser,dbPassword,output,moduleName,author);
    }


    public static void generator(List<String> tables,String host,int port,String dbName,String dbUser,String dbPassword,String output,String moduleName,String author) {

        List<CustomFile> customFileList = new ArrayList<>();
        customFileList.add(new CustomFile.Builder().packageName("req").fileName("Req.java").templatePath("/templates/req.java.vm").enableFileOverride().build());
        customFileList.add(new CustomFile.Builder().packageName("vo").fileName("Vo.java").templatePath("/templates/vo.java.vm").enableFileOverride().build());

        FastAutoGenerator
                //1、配置数据源
                .create("jdbc:mysql://"+host+":"+port+"/"+dbName+"?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC&useSSL=false",
                dbUser,
                dbPassword)
                .dataSourceConfig(builder ->
                        builder.typeConvertHandler((globalConfig, typeRegistry, metaInfo) -> {
                            int typeCode = metaInfo.getJdbcType().TYPE_CODE;
                            if (typeCode == JdbcType.TINYINT.TYPE_CODE) {
                                // 自定义类型转换
                                return DbColumnType.INTEGER;
                            }
                            return typeRegistry.getColumnType(metaInfo);
                        })
                )
                //2、全局配置
                .globalConfig(builder -> {
                    builder.author(author)               //作者
                            .outputDir(output)    //输出路径(写到java目录)
                            .enableSpringdoc()
                            .dateType(DateType.ONLY_DATE)
                            .commentDate("yyyy-MM-dd HH:mm")
//                            .fileOverride()           //开启覆盖之前生成的文件
                    ;

                })
                //3、包配置
                .packageConfig(builder -> {
                    builder.parent("com.ubxtech")
                            .moduleName(moduleName)
                            .entity("entity")
                            .service("service")
                            .serviceImpl("service.impl")
                            .controller("controller")
                            .mapper("mapper")
                            .xml("mapper")
                            .pathInfo(Collections.singletonMap(OutputFile.xml,output));
                    builder.joinPackage("base");
                })
                //4、策略配置
                .strategyConfig(builder -> {
                    builder.addInclude(tables)
//                            .addTablePrefix("t_")
                            .serviceBuilder().enableFileOverride()
                            .formatServiceFileName("%sService")
                            .formatServiceImplFileName("%sServiceImpl")

                            .entityBuilder()
                            .superClass(Entity.class)
                            .enableLombok()
                            .enableFileOverride()
                            .logicDeleteColumnName("delete_flag")
                            .enableTableFieldAnnotation() // 启用字段注解
                            .naming(NamingStrategy.underline_to_camel)
                            .columnNaming(NamingStrategy.underline_to_camel)

                            .controllerBuilder()
                            .formatFileName("%sController")
                            .enableFileOverride()
                            .enableRestStyle()

                            .mapperBuilder()
                            .enableBaseResultMap()  //生成通用的resultMap
                            .enableFileOverride()
                            .superClass(BaseMapper.class)
                            .formatMapperFileName("%sMapper")
                            .formatXmlFileName("%sMapper")
                    ;
                })
                .injectionConfig(builder -> builder
                        .beforeOutputFile((tableInfo, objectMap) -> {
                            System.out.println("tableInfo: " + tableInfo.getEntityName() + " objectMap: " + objectMap.size());
                        })
                        //自定义配置 Map 对象
                        .customMap(Collections.singletonMap("my_field", "自己注入属性"))
                        //自定义配置模板文件
                        .customFile(customFileList) //自定义配置模板文件

                        .build()
                )
//                .templateConfig(templateConfigBuilder ->
//                        templateConfigBuilder
//                        .disable(TemplateType.CONTROLLER)
//                        .controller("templates/Controller.java.vm")
//                )
                //5、模板引擎配置 VelocityTemplateEngine  FreemarkerTemplateEngine  默认的是Velocity引擎模板
                .templateEngine(new CustomVelocityTemplateEngine())
                .execute();

    }

    public static void main(String[] args) {
        CodeGenerator.generator(
                Arrays.asList("sys_user"),
                "10.10.17.153",
                3307,
                "bi_sys",
                "cml_dev",
                "cml_dev",
                "D://codegernerate",
                "bi.user",
                "Victor.xiao"
        );


    }
}
